package com.github.wxiaoqi.security.crm.core.biz;

import java.math.BigDecimal;
import java.text.Bidi;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.common.crm.request.BalanceOutAccountRequest;
import com.github.wxiaoqi.security.common.crm.request.OutAccountRequest;
import com.github.wxiaoqi.security.common.crm.request.RefundFreezeRequest;
import com.github.wxiaoqi.security.common.crm.request.RefundUnFreezeRequest;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.crm.core.entity.FreezeJournal;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccount;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccountJournal;
import com.github.wxiaoqi.security.crm.core.entity.PersonalAccount;
import com.github.wxiaoqi.security.crm.core.entity.PersonalAccountJournal;
import com.github.wxiaoqi.security.crm.core.entity.PersonalBilling;
import com.github.wxiaoqi.security.crm.core.entity.UnfreezeJournal;
import com.github.wxiaoqi.security.crm.core.mapper.FreezeJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantAccountJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantAccountMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalAccountJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalAccountMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalBillingMapper;
import com.github.wxiaoqi.security.crm.core.mapper.UnfreezeJournalMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 退款相关的操作接口--退款时不需要审核直接出账(包括第三方支付和余额账户支付 发起的退款)
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class RefundOutAccountBiz {
	@Autowired
	private PersonalBillingMapper personalBillingMapper;
	@Autowired
	private MerchantAccountJournalMapper merchantAccountJournalMapper;
	@Autowired
	private MerchantAccountMapper merchantAccountMapper;
	@Autowired
	private PersonalAccountMapper personalAccountMapper;
	@Value("${bountyHunter.balanceSaltValue}")
	private String balanceSaltValue;
	@Autowired
	private PersonalAccountJournalMapper personalAccountJournalMapper;
	/**
	 * 第三方支付-退款时不需要审核直接出账接口 
	 * 1.商户账户余额扣除，2.新增商户账户流水，新增个人账单成功记录
	 */
	public Map<String, Object> outAccount(OutAccountRequest outAccountRequest) {
		log.info("退款时（第三方支付）不需要审核直接出账接口  -请求参数：{}" + EntityUtils.beanToMap(outAccountRequest));
		Map<String, Object> response = new HashMap<String, Object>();
		/**
		 * 根据订单号获取个人账单中获取支付金额A
		 * 根据订单号从商户账户流水表中获取商户退款出账合计金额B 
		 * 本次请求出账金额C 若(B+C)>A
		 * 则不能再次出账本次订单
		 */
		PersonalBilling perBill = new PersonalBilling();
		perBill.setPlatformId(outAccountRequest.getPlatformId());
		perBill.setPersonalId(outAccountRequest.getPersonalId());
		perBill.setOrderNo(outAccountRequest.getPayOrderNo());
		perBill.setInOutFlag("2");//出账
		perBill.setStatus("00");// 支付成功
		PersonalBilling perPayBill=personalBillingMapper.selectOne(perBill);
		if(null!=perPayBill){
		/***
		 * 获取实际出账金额合计
		 * */
		try {
			MerchantAccountJournal merAccountJournal=new MerchantAccountJournal();
			merAccountJournal.setPlatformId(outAccountRequest.getPlatformId());
			merAccountJournal.setMerchantId(outAccountRequest.getMerchantId());
			merAccountJournal.setOrderNo(outAccountRequest.getRefundOrderNo());
			BigDecimal refoundCount=merchantAccountJournalMapper.merAccountRefoundCount(merAccountJournal);
			log.info("发起退款时--出账金额"+perPayBill.getTradeAmt()+"--="+"商户账户流水表中实际出账金额合计金额"+refoundCount+"+本次退款需出账金额"+outAccountRequest.getRefoundAmt());
			if((new BigDecimal(outAccountRequest.getRefoundAmt()).add(refoundCount)).compareTo(perPayBill.getTradeAmt())>0){
				log.info("退款时（第三方支付）不需要审核直接出账接口--支付订单不存在");
				response.put("code", ResponseCode.MER_ACCOUNT_JOURNAL_NOTEXIST.getCode());
				response.put("msg", ResponseCode.MER_ACCOUNT_JOURNAL_NOTEXIST.getMessage());
				return response;
			}
			/**
			 * 修改商户账户余额
			 * */
			MerchantAccount queryMerchantAccount=new MerchantAccount();
			queryMerchantAccount.setPlatformId(outAccountRequest.getPlatformId());
			queryMerchantAccount.setMerchantId(outAccountRequest.getMerchantId());
			queryMerchantAccount.setCustomerType(outAccountRequest.getCustomerType());
			queryMerchantAccount.setAccountType(outAccountRequest.getAccountType());
			MerchantAccount merchantAccount= merchantAccountMapper.selectOne(queryMerchantAccount);
			if(null!=merchantAccount){
				//校验商户账户余额是否匹配  和商户账户余额是否充足
				if(!MD5.sign(merchantAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8").equals(merchantAccount.getCheckSum())){
					response.put("code", ResponseCode.MER_ACC_BALANCE_NOT_MATE.getCode());
					response.put("msg", ResponseCode.MER_ACC_BALANCE_NOT_MATE.getMessage());
					log.info("退款时（第三方支付）不需要审核直接出账接口 返回参数。。。。。。{}", response);
					return response;
				}
				if(!MD5.sign(merchantAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8").equals(new BigDecimal(outAccountRequest.getRefoundAmt()))){
					response.put("code", ResponseCode.MER_ACC_BALANCE_NOT_ENOUGH.getCode());
					response.put("msg", ResponseCode.MER_ACC_BALANCE_NOT_ENOUGH.getMessage());
					log.info("退款时（第三方支付）不需要审核直接出账接口返回参数。。。。。。{}", response);
					return response;
				}
				merchantAccount.setAccountBalance(queryMerchantAccount.getAccountBalance().subtract(new BigDecimal(outAccountRequest.getRefoundAmt())));
				merchantAccountMapper.updateByPrimaryKeySelective(merchantAccount);
			}else{
				log.info("退款时（第三方支付）不需要审核直接出账接口--商户账户不存在");
				response.put("code", ResponseCode.MER_ACC_NOTEXIST.getCode());
				response.put("msg", ResponseCode.MER_ACC_NOTEXIST.getMessage());
				return response;
			}
			/***
			 * 新增商户账户流水记录 和个人账单退款成功记录
			 * */
			merAccountJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			merAccountJournal.setPlatformId(outAccountRequest.getPlatformId());
			merAccountJournal.setMerchantId(outAccountRequest.getMerchantId());
			merAccountJournal.setAccountId(merchantAccount.getAccountId());
			merAccountJournal.setOrderNo(outAccountRequest.getRefundOrderNo());
			merAccountJournal.setInOutFlag("2");//出账 
			merAccountJournal.setTradeAmt(new BigDecimal(outAccountRequest.getRefoundAmt()));
			merAccountJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			merAccountJournal.setCreateTime(new Date());
			merchantAccountJournalMapper.insertSelective(merAccountJournal);
			PersonalBilling billing = new PersonalBilling();
			billing.setBillId(String.valueOf(SnowFlake.getId()));
			billing.setPlatformId(outAccountRequest.getPlatformId());
			billing.setOrderNo(outAccountRequest.getRefundOrderNo());
			//billing.setBillType("");
			billing.setInOutFlag("1");
			billing.setTradeAmt(new BigDecimal(outAccountRequest.getRefoundAmt()));
			billing.setSellerType(outAccountRequest.getCustomerType());
			billing.setProduceInfo(outAccountRequest.getProduceInfo());
			billing.setPayWay(outAccountRequest.getPayType());
			billing.setCreateTime(new Date());
			billing.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			billing.setStatus("03");//账单状态（付款成功 00 ，充值成功 01 ，退款申请成功02，退款成功03， 提现申请成功04 ，提现处理成功 05 ）
			personalBillingMapper.insertSelective(billing);
			response.put("code", ResponseCode.OK.getCode());
			response.put("msg", ResponseCode.OK.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			log.info("退款时（第三方支付）不需要审核直接出账接口 报错--"+e.getMessage());
			response.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			response.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
			return response;
		}
		}else{
			log.info("退款时（第三方支付）不需要审核直接出账接口--支付订单不存在");
			response.put("code", ResponseCode.PER_PAYBILL_NOT_EXIST.getCode());
			response.put("msg", ResponseCode.PER_PAYBILL_NOT_EXIST.getMessage());
			return response;
		}
		return response;
	}
	/**
	 * 余额账户支付退款不需要审核时直接出账接口
	 * 1.商户账户余额扣除，个人账户余额增加;
	 * 2.新增商户账户流水，新增个人账单成功记录
	 * 3.新增个人账户流水记录
	 */
	public Map<String, Object> balanceOutAccount(BalanceOutAccountRequest balanceOutAccountRequest) {
		log.info("退款时（余额账户支付）不需要审核直接出账接口  -请求参数：{}" + EntityUtils.beanToMap(balanceOutAccountRequest));
		Map<String, Object> response = new HashMap<String, Object>();
		/**
		 * 根据订单号获取个人账单中获取支付金额A
		 * 根据订单号从商户账户流水表中获取商户退款出账合计金额B 
		 * 本次请求出账金额C 若(B+C)>A
		 * 则不能再次出账本次订单
		 */
		PersonalBilling perBill = new PersonalBilling();
		perBill.setPlatformId(balanceOutAccountRequest.getPlatformId());
		perBill.setPersonalId(balanceOutAccountRequest.getPersonalId());
		perBill.setOrderNo(balanceOutAccountRequest.getPayOrderNo());
		perBill.setInOutFlag("2");//出账
		perBill.setStatus("00");// 支付成功
		PersonalBilling perPayBill=personalBillingMapper.selectOne(perBill);
		if(null!=perPayBill){
		/***
		 * 获取实际出账金额合计
		 * */
		try {
			MerchantAccountJournal merAccountJournal=new MerchantAccountJournal();
			merAccountJournal.setPlatformId(balanceOutAccountRequest.getPlatformId());
			merAccountJournal.setMerchantId(balanceOutAccountRequest.getMerchantId());
			merAccountJournal.setOrderNo(balanceOutAccountRequest.getRefundOrderNo());
			BigDecimal refoundCount=merchantAccountJournalMapper.merAccountRefoundCount(merAccountJournal);
			log.info("发起退款时--出账金额"+perPayBill.getTradeAmt()+"--="+"商户账户流水表中实际出账金额合计金额"+refoundCount+"+本次退款需出账金额"+balanceOutAccountRequest.getRefoundAmt());
			if((new BigDecimal(balanceOutAccountRequest.getRefoundAmt()).add(refoundCount)).compareTo(perPayBill.getTradeAmt())>0){
				log.info("退款时（余额账户支付）不需要审核直接出账接口--支付订单不存在");
				response.put("code", ResponseCode.MER_ACCOUNT_JOURNAL_NOTEXIST.getCode());
				response.put("msg", ResponseCode.MER_ACCOUNT_JOURNAL_NOTEXIST.getMessage());
				return response;
			}
			/**
			 * 商户账户余额扣除
			 * */
			MerchantAccount queryMerchantAccount=new MerchantAccount();
			queryMerchantAccount.setPlatformId(balanceOutAccountRequest.getPlatformId());
			queryMerchantAccount.setMerchantId(balanceOutAccountRequest.getMerchantId());
			queryMerchantAccount.setCustomerType(balanceOutAccountRequest.getCustomerType());
			queryMerchantAccount.setAccountType(balanceOutAccountRequest.getAccountType());
			MerchantAccount merchantAccount= merchantAccountMapper.selectOne(queryMerchantAccount);
			if(null!=merchantAccount){
				//校验商户账户余额是否匹配  和商户账户余额是否充足
				if(!MD5.sign(merchantAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8").equals(merchantAccount.getCheckSum())){
					response.put("code", ResponseCode.MER_ACC_BALANCE_NOT_MATE.getCode());
					response.put("msg", ResponseCode.MER_ACC_BALANCE_NOT_MATE.getMessage());
					log.info("退款时（余额账户支付）不需要审核直接出账接口 返回参数。。。。。。{}", response);
					return response;
				}
				if(!MD5.sign(merchantAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8").equals(new BigDecimal(balanceOutAccountRequest.getRefoundAmt()))){
					response.put("code", ResponseCode.MER_ACC_BALANCE_NOT_ENOUGH.getCode());
					response.put("msg", ResponseCode.MER_ACC_BALANCE_NOT_ENOUGH.getMessage());
					log.info("退款时（余额账户支付）不需要审核直接出账接口返回参数。。。。。。{}", response);
					return response;
				}
				merchantAccount.setAccountBalance(queryMerchantAccount.getAccountBalance().subtract(new BigDecimal(balanceOutAccountRequest.getRefoundAmt())));
				merchantAccountMapper.updateByPrimaryKeySelective(merchantAccount);
			}else{
				log.info("退款时（余额账户支付）不需要审核直接出账接口--商户账户不存在");
				response.put("code", ResponseCode.MER_ACC_NOTEXIST.getCode());
				response.put("msg", ResponseCode.MER_ACC_NOTEXIST.getMessage());
				return response;
			}
			/**
			 * 个人账户余额增加
			 * */
			PersonalAccount queryPersonalAccount = new PersonalAccount();
			queryPersonalAccount.setPlatformId(balanceOutAccountRequest.getPlatformId());
			queryPersonalAccount.setPersonalId(balanceOutAccountRequest.getPersonalId());
			queryPersonalAccount.setAccountType(balanceOutAccountRequest.getAccountType());
			PersonalAccount personalAccount = personalAccountMapper.selectOne(queryPersonalAccount);
			if(null!=personalAccount){
				if(!MD5.sign(personalAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8").equals(personalAccount.getCheckSum())){
					response.put("code", ResponseCode.PER_ACC_BALANCE_NOT_MATE.getCode());
					response.put("msg", ResponseCode.PER_ACC_BALANCE_NOT_MATE.getMessage());
					log.info("退款时（余额账户支付）不需要审核直接出账接口 返回参数。。。。。。{}", response);
					return response;
				}
				personalAccount.setAccountBalance(personalAccount.getAccountBalance().add(new BigDecimal(balanceOutAccountRequest.getRefoundAmt())));
				personalAccount.setCheckSum(MD5.sign(personalAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8"));
				personalAccountMapper.updateByPrimaryKeySelective(personalAccount);
			}else{
				log.info("退款时（余额账户支付）不需要审核直接出账接口--个人账户不存在");
				response.put("code", ResponseCode.PER_ACC_NOTEXIST.getCode());
				response.put("msg", ResponseCode.PER_ACC_NOTEXIST.getMessage());
				return response;
			}
			/***
			 * 新增商户账户流水记录 和个人账单退款成功记录及个人账户流水记录
			 * */
			merAccountJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			merAccountJournal.setPlatformId(balanceOutAccountRequest.getPlatformId());
			merAccountJournal.setMerchantId(balanceOutAccountRequest.getMerchantId());
			merAccountJournal.setAccountId(merchantAccount.getAccountId());
			merAccountJournal.setOrderNo(balanceOutAccountRequest.getRefundOrderNo());
			merAccountJournal.setInOutFlag("2");//出账 
			merAccountJournal.setTradeAmt(new BigDecimal(balanceOutAccountRequest.getRefoundAmt()));
			merAccountJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			merAccountJournal.setCreateTime(new Date());
			merchantAccountJournalMapper.insertSelective(merAccountJournal);
			PersonalBilling billing = new PersonalBilling();
			billing.setBillId(String.valueOf(SnowFlake.getId()));
			billing.setPlatformId(balanceOutAccountRequest.getPlatformId());
			billing.setOrderNo(balanceOutAccountRequest.getRefundOrderNo());
			//billing.setBillType("");
			billing.setInOutFlag("1");
			billing.setTradeAmt(new BigDecimal(balanceOutAccountRequest.getRefoundAmt()));
			billing.setSellerType(balanceOutAccountRequest.getCustomerType());
			billing.setProduceInfo(balanceOutAccountRequest.getProduceInfo());
			billing.setPayWay(balanceOutAccountRequest.getPayType());
			billing.setCreateTime(new Date());
			billing.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			billing.setStatus("03");//账单状态（付款成功 00 ，充值成功 01 ，退款申请成功02，退款成功03， 提现申请成功04 ，提现处理成功 05 ）
			personalBillingMapper.insertSelective(billing);
			/***
			 * 新增个人账户流水记录
			 * */
			PersonalAccountJournal personalAccountJournal=new PersonalAccountJournal();
			personalAccountJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			personalAccountJournal.setPlatformId(balanceOutAccountRequest.getPlatformId());
			personalAccountJournal.setPersonalId(balanceOutAccountRequest.getPersonalId());
			personalAccountJournal.setAccountId(personalAccount.getAccountId());
			personalAccountJournal.setAccountType(personalAccount.getAccountType());
			personalAccountJournal.setOrderNo(balanceOutAccountRequest.getRefundOrderNo());
			personalAccountJournal.setInOutFlag("1");//来往标志  1：入账   2：出账
			personalAccountJournal.setTradeAmt(new BigDecimal(balanceOutAccountRequest.getRefoundAmt()));
			personalAccountJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			personalAccountJournal.setCreateTime(new Date());
			personalAccountJournalMapper.insertSelective(personalAccountJournal);
			response.put("code", ResponseCode.OK.getCode());
			response.put("msg", ResponseCode.OK.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			log.info("退款时（余额账户支付）不需要审核直接出账接口 报错--"+e.getMessage());
			response.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			response.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
			return response;
		}
		}else{
			log.info("退款时（余额账户支付）不需要审核直接出账接口--支付订单不存在");
			response.put("code", ResponseCode.PER_PAYBILL_NOT_EXIST.getCode());
			response.put("msg", ResponseCode.PER_PAYBILL_NOT_EXIST.getMessage());
			return response;
		}
		return response;
		
	}
}
